package com.indsvr.web.controller.system;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.indsvr.common.constant.Constants;
import com.indsvr.common.core.domain.entity.SysUser;
import com.indsvr.common.utils.AesUtils;
import com.indsvr.common.utils.MessageUtils;
import com.indsvr.framework.manager.AsyncManager;
import com.indsvr.framework.manager.factory.AsyncFactory;
import com.indsvr.framework.shiro.service.SysLoginService;
import com.indsvr.framework.web.domain.server.Sys;
import com.indsvr.system.service.ISysUserService;
import com.indsvr.system.task.UserTask;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.BearerToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.indsvr.common.core.controller.BaseController;
import com.indsvr.common.core.domain.AjaxResult;
import com.indsvr.common.core.text.Convert;
import com.indsvr.common.utils.ServletUtils;
import com.indsvr.common.utils.StringUtils;
import com.indsvr.framework.web.service.ConfigService;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录验证
 *
 * @author indsvr
 */
@Controller
public class SysLoginController extends BaseController {
    /**
     * 是否开启记住我功能
     */
    @Value("${shiro.rememberMe.enabled: false}")
    private boolean rememberMe;

    @Autowired
    private ConfigService configService;

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, ModelMap mmap) {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)) {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        // 是否开启记住我
        mmap.put("isRemembered", rememberMe);
        // 是否开启用户注册
        mmap.put("isAllowRegister", Convert.toBool(configService.getKey("sys.account.registerUser"), false));
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return success();
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    @RequestMapping("/loginV2")
    @ResponseBody
    public AjaxResult ajaxLogin(@RequestBody LoginEntity loginEntity) {
        return ajaxLogin(loginEntity.username,loginEntity.password,false);
    }

    @GetMapping("/isLogin")
    @ResponseBody
    public AjaxResult isLogin() {
        return success();
    }

    private static class LoginEntity{
        private String username;
        private String password;

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }



    @Autowired
    private ISysUserService userService;

    @ResponseBody
    @RequestMapping("/loginApi")
    public AjaxResult loginApi(@RequestParam String key,String type,HttpServletResponse response) throws Exception {

        long l = System.currentTimeMillis() / 100000;


        String configKey = configService.getKey("sso.key")+l;


        key=new String(Base64.getDecoder().decode(key));

        String decrypt = "";

        try {
            decrypt=AesUtils.decrypt(key, configKey);
        }catch (Exception e){
            return error("密钥过时"+l);
        }


        SysUser user = userService.selectUserByLoginName(decrypt);

        if (user==null) {
            return error("用户不存在");
        }

        UsernamePasswordToken token = new UsernamePasswordToken(decrypt, user.getPassword(), rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);

            if ("301".equals(type)) {
                response.sendRedirect("/");
            }

            return success();
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    @GetMapping("/unauth")
    public String unauth() {
        return "error/unauth";
    }
}
